package com.suning.sawp.web.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.suning.framework.image.service.ImageServiceException;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.dto.common.RecordList;
import com.suning.sawp.dto.mainpush.StoreManDto;
import com.suning.sawp.intf.storeman.StoreManService;
import com.suning.sawp.po.contend.CommBean;
import com.suning.sawp.po.contend.CommPersonDTO;
import com.suning.sawp.po.contend.NmLibBean;
import com.suning.sawp.po.contend.PersonBean;
import com.suning.sawp.po.contend.TopicBean;
import com.suning.sawp.po.contend.TopicVoteDTO;
import com.suning.sawp.po.contend.VoteTopicRel;
import com.suning.sawp.po.contend.WxUserInfo;
import com.suning.sawp.service.impl.contend.ContendService;
import com.suning.sawp.service.impl.contend.UIMGStore;
import com.suning.sawp.service.util.BaseContants;
import com.suning.sawp.web.exception.MyGsonView;

/**
 * 
 * 〈苏宁争鸣〉<br>
 * 〈功能详细描述〉
 *
 * @author 12061748
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/contend")
public class ContendController extends DjBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(OutGrowController.class);

    @Autowired
    ContendService contendService;

    @Autowired
    UIMGStore uimgStore;

    @Autowired
    StoreManService storeManService;

    /**
     * 
     * 功能描述:查询话题列表<br>
     *
     * @param principal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/queryAllTopic.htm", produces = "application/json; charset=utf-8")
    public MyGsonView queryAllTopic(Integer start, Integer limit) {
        MyGsonView gsonView = createGsonView();
        try {
            List<TopicBean> topicList = contendService.queryTopicList(start, limit, "");
            gsonView.addStaticAttribute(BaseContants.DATA, topicList);
        } catch (Exception e) {
            LOGGER.error("queryAllTopic error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:oa登录用户访问的话题详情页 <br>
     * 〈功能详细描述〉
     *
     * @param topicId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/soaTopic/index.do", produces = "application/json; charset=utf-8")
    public void oaQeryTopicDetail(String redirectUrl, HttpServletRequest request, HttpServletResponse response) {
        StringBuilder url = new StringBuilder(redirectUrl).append("&isLogin=1");
        try {
            response.sendRedirect(url.toString());
        } catch (UnsupportedEncodingException e1) {
            LOGGER.error("", e1);
        } catch (IOException e) {
            LOGGER.error("", e);
        }
    }

    /**
     * 
     * 功能描述: 获取用户信息<br>
     * 〈功能详细描述〉
     *
     * @param principal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/soaTopic/loginInfo.do", produces = "application/json; charset=utf-8")
    public MyGsonView soaTopicLoginInfo(Principal principal) {
        MyGsonView gsonView = createGsonView();
        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 没有用户则创建一个新用户
        PersonBean person = contendService.querySoaPersonBeanInfo(principal.getName(), storeManDto.getStaffName());
        gsonView.addStaticAttribute(BaseContants.DATA, person);
        return gsonView;
    }

    /**
     * 
     * 功能描述:微信用户访问的话题详情页 <br>
     * 〈功能详细描述〉
     *
     * @param topicId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/wxTopic/index.htm", produces = "application/json; charset=utf-8")
    public MyGsonView wxTopicIndex(Model model, WxUserInfo wxUserInfo, String topicId) {
        MyGsonView gsonView = createGsonView();
        model.addAttribute("wxUserInfo", null);
        if (StringUtils.isBlank(topicId) || wxUserInfo == null || StringUtils.isBlank(wxUserInfo.getOpenId())) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        }
        try {
            // 通过openId查询用户id,没有则创建一个
            PersonBean person = contendService.queryWxPersonBeanInfo(wxUserInfo);
            // 查询话题详情
            TopicVoteDTO bean = contendService.queryTopicDetail(topicId, person.getPersonId());
            gsonView.addStaticAttribute(BaseContants.DATA, bean);
        } catch (Exception e) {
            LOGGER.error("wxTopic/index.htm error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述: 查询话题信息<br>
     * 〈功能详细描述〉
     *
     * @param personId
     * @param topicId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/soaTopic/query.do", produces = "application/json; charset=utf-8")
    public MyGsonView soaTopicQuery(Principal principal, String topicId) {
        MyGsonView gsonView = createGsonView();
        PersonBean person = contendService.querySoaPersonInfo(principal.getName());
        if (StringUtils.isBlank(topicId) || person == null || person.getPersonId() == null) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        }
        try {
            // 查询话题详情
            TopicVoteDTO bean = contendService.queryTopicDetail(topicId, person.getPersonId());
            gsonView.addStaticAttribute(BaseContants.DATA, bean);
        } catch (Exception e) {
            LOGGER.error("soaTopic error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:查询评论列表 <br>
     * 〈功能详细描述〉
     *
     * @param model
     * @param personId
     * @param topicId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/soaTopic/queryCommList.do", produces = "application/json; charset=utf-8")
    public MyGsonView queryCommList(Principal principal, String topicId, Integer start, Integer limit) {
        MyGsonView gsonView = createGsonView();
        PersonBean person = contendService.querySoaPersonInfo(principal.getName());
        if (StringUtils.isBlank(topicId) || person == null || person.getPersonId() == null) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        }
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (start == 0) {
                List<CommPersonDTO> bestCommList = contendService.queryBestCommList(topicId);
                // 查询最强声列表
                result.put("bestCommList", bestCommList);
            }
            RecordList<CommPersonDTO> commList = contendService.queryCommList(start, limit, topicId,
                    String.valueOf(person.getPersonId()));
            result.put("commList", commList);
            gsonView.addStaticAttribute(BaseContants.DATA, result);
        } catch (Exception e) {
            LOGGER.error("queryCommList error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:查询评论列表 <br>
     * 〈功能详细描述〉
     *
     * @param model
     * @param personId
     * @param topicId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/wxTopic/queryCommList.htm", produces = "application/json; charset=utf-8")
    public MyGsonView queryCommList(String topicId, Integer start, Integer limit, Model model, WxUserInfo wxUserInfo) {
        MyGsonView gsonView = createGsonView();
        model.addAttribute("wxUserInfo", null);
        PersonBean wxPerson = contendService.queryWxPersonInfo(wxUserInfo);
        if (StringUtils.isBlank(topicId) || wxPerson == null || wxPerson.getPersonId() == null) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        }
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (start == 0) {
                List<CommPersonDTO> bestCommList = contendService.queryBestCommList(topicId);
                // 查询最强声列表
                result.put("bestCommList", bestCommList);
            }
            RecordList<CommPersonDTO> commList = contendService.queryCommList(start, limit, topicId,
                    String.valueOf(wxPerson.getPersonId()));
            result.put("commList", commList);
            gsonView.addStaticAttribute(BaseContants.DATA, result);
        } catch (Exception e) {
            LOGGER.error("queryCommList error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:上传图片 <br>
     * 〈功能详细描述〉
     *
     * @param multipartRequest
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/uploadMisc.htm", produces = "application/json;charset=utf-8")
    @ResponseBody
    public MyGsonView uploadMisc(MultipartRequest multipartRequest) {
        MyGsonView gsonView = createGsonView();
        MultipartFile imageFile = multipartRequest.getFile("image");
        if (null != imageFile && !imageFile.isEmpty() && null != imageFile.getContentType()) {
            MediaType mediaType = MediaType.parseMediaType(imageFile.getContentType());
            List<MediaType> supports = MediaType.parseMediaTypes("image/*");
            for (MediaType support : supports) {
                if (support.includes(mediaType)) {
                    String imgUrl;
                    InputStream in = null;
                    try {
                        in = imageFile.getInputStream();
                        imgUrl = uimgStore
                                .onlyUpload(UIMGStore.FileType.MISC, mediaType.getSubtype().toLowerCase(), in);
                        gsonView.addStaticAttribute(BaseContants.DATA, imgUrl);
                    } catch (ImageServiceException e) {
                        LOGGER.error("UMIG服务异常", e);
                        setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
                    } catch (IOException ex) {
                        LOGGER.error("UMIG服务异常", ex);
                        setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
                    } finally {
                        IOUtils.closeQuietly(in);
                    }
                    break;
                }
                setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            }
        } else {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:发表评论 <br>
     * 〈功能详细描述〉
     *
     * @param multipartRequest
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/wxTopic/comment.htm", produces = "application/json;charset=utf-8")
    @ResponseBody
    public MyGsonView comment(Model model, WxUserInfo wxUserInfo, CommBean commBean) {
        MyGsonView gsonView = createGsonView();
        model.addAttribute("commBean", null);
        model.addAttribute("wxUserInfo", null);
        PersonBean wxPerson = contendService.queryWxPersonInfo(wxUserInfo);
        if (wxPerson == null || wxPerson.getPersonId() == null) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        }
        try {
            commBean.setPersonId(wxPerson.getPersonId());
            if (!CommBean.TypeConstants.TYPE_NM.equals(commBean.getCriticType())) {
                commBean.setCriticType(CommBean.TypeConstants.TYPE_WX);
            }
            // 查询话题详情
            TopicVoteDTO bean = contendService.queryTopicDetail(commBean.getTopicId(), wxPerson.getPersonId());
            commBean.setViewPoint(bean.getViewPoint());
            contendService.saveComment(commBean);
            gsonView.addStaticAttribute(BaseContants.DATA, "");
        } catch (Exception e) {
            LOGGER.error("comment error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:oa用户发表评论 <br>
     * 〈功能详细描述〉
     *
     * @param model
     * @param commBean
     * @param principal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/soaTopic/comment.do", produces = "application/json;charset=utf-8")
    @ResponseBody
    public MyGsonView comment(Model model, CommBean commBean, Principal principal) {
        MyGsonView gsonView = createGsonView();
        model.addAttribute("commBean", null);
        PersonBean person = contendService.querySoaPersonInfo(principal.getName());
        if (person == null || person.getPersonId() == null) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        }
        try {
            commBean.setPersonId(person.getPersonId());
            // 查询话题详情
            TopicVoteDTO bean = contendService.queryTopicDetail(commBean.getTopicId(), person.getPersonId());
            commBean.setViewPoint(bean.getViewPoint());
            if (!CommBean.TypeConstants.TYPE_NM.equals(commBean.getCriticType())) {
                commBean.setCriticType(CommBean.TypeConstants.TYPE_SOA);
            }
            contendService.saveComment(commBean);
            gsonView.addStaticAttribute(BaseContants.DATA, "");
        } catch (Exception e) {
            LOGGER.error("comment error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:获取匿名信息（姓名和头像） <br>
     * 〈功能详细描述〉
     *
     * @param commBean
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/getNmInfo.htm", produces = "application/json;charset=utf-8")
    @ResponseBody
    public MyGsonView getNmInfo() {
        MyGsonView gsonView = createGsonView();
        try {
            List<NmLibBean> list = contendService.getNmInfo();
            Map<String, Object> result = new HashMap<String, Object>();
            if (CollectionUtils.isEmpty(list)) {
                setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
            } else {
                for (NmLibBean lib : list) {
                    if (NmLibBean.TypeConstants.TYPE_NAME.equals(lib.getType())) {
                        result.put("name", lib.getName());
                    } else {
                        result.put("headPic", lib.getName());
                    }
                }
                gsonView.addStaticAttribute(BaseContants.DATA, result);
            }

        } catch (Exception e) {
            LOGGER.error("getNmInfo error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述: 修改用户头像<br>
     * 〈只能修改oa用户的头像〉
     *
     * @param personId
     * @param headPic
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/soaTopic/modifyUserHeadPic.do", produces = "application/json;charset=utf-8")
    @ResponseBody
    public MyGsonView modifyUserHeadPic(Model model, String headPic, Principal principal) {
        MyGsonView gsonView = createGsonView();
        PersonBean person = contendService.querySoaPersonInfo(principal.getName());
        if (StringUtils.isBlank(headPic) || person == null || person.getPersonId() == null) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        }
        try {
            person.setHeadPic(headPic);
            contendService.modifyUserInfo(person);
            gsonView.addStaticAttribute(BaseContants.DATA, "");
        } catch (Exception e) {
            LOGGER.error("modifyUserHeadPic error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:参与话题 <br>
     * 〈投票〉
     *
     * @param personId
     * @param topicId
     * @param viewPoint
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/soaTopic/topicVote.do", produces = "application/json;charset=utf-8")
    @ResponseBody
    public MyGsonView topicVote(Model model, VoteTopicRel voteTopicRel, Principal principal) {
        MyGsonView gsonView = createGsonView();
        model.addAttribute("voteTopicRel", null);
        PersonBean person = contendService.querySoaPersonInfo(principal.getName());
        if (person.getPersonId() == null || voteTopicRel.getTopicId() == null
                || StringUtils.isBlank(voteTopicRel.getViewPoint())) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        }
        try {
            voteTopicRel.setPersonId(person.getPersonId());
            contendService.topicVote(voteTopicRel);
            gsonView.addStaticAttribute(BaseContants.DATA, "");
        } catch (Exception e) {
            LOGGER.error("topicVote error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:参与话题 <br>
     * 〈投票〉
     *
     * @param personId
     * @param topicId
     * @param viewPoint
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/wxTopic/topicVote.htm", produces = "application/json;charset=utf-8")
    @ResponseBody
    public MyGsonView wxTopicTopicVote(Model model, VoteTopicRel voteTopicRel, WxUserInfo wxUserInfo) {
        MyGsonView gsonView = createGsonView();
        model.addAttribute("voteTopicRel", null);
        model.addAttribute("wxUserInfo", null);
        PersonBean wxPerson = contendService.queryWxPersonInfo(wxUserInfo);
        if (wxPerson.getPersonId() == null || voteTopicRel.getTopicId() == null
                || StringUtils.isBlank(voteTopicRel.getViewPoint())) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        }
        try {
            voteTopicRel.setPersonId(wxPerson.getPersonId());
            contendService.topicVote(voteTopicRel);
            gsonView.addStaticAttribute(BaseContants.DATA, "");
        } catch (Exception e) {
            LOGGER.error("topicVote error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:踩和赞评论 <br>
     * 〈功能详细描述〉
     *
     * @param commId
     * @param isZan
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/commVote.htm", produces = "application/json;charset=utf-8")
    @ResponseBody
    public MyGsonView commVote(String commId, Boolean isZan) {
        MyGsonView gsonView = createGsonView();
        if (StringUtils.isBlank(commId)) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        }
        try {
            contendService.commVote(commId, isZan);
            gsonView.addStaticAttribute(BaseContants.DATA, "");
        } catch (Exception e) {
            LOGGER.error("commVote error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:删除评论 <br>
     * 〈功能详细描述〉
     *
     * @param commId
     * @param isZan
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/wxTopic/delComm.htm", produces = "application/json;charset=utf-8")
    @ResponseBody
    public MyGsonView delComm(Model model, String commId, WxUserInfo wxUserInfo) {
        MyGsonView gsonView = createGsonView();
        model.addAttribute("wxUserInfo", null);
        PersonBean wxPerson = contendService.queryWxPersonInfo(wxUserInfo);
        if (StringUtils.isBlank(commId) || wxPerson == null || wxPerson.getPersonId() == null) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        }
        try {
            contendService.delComm(commId, wxPerson.getPersonId());
            gsonView.addStaticAttribute(BaseContants.DATA, "");
        } catch (Exception e) {
            LOGGER.error("delComm error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:删除评论 <br>
     * 〈功能详细描述〉
     *
     * @param commId
     * @param isZan
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/soaTopic/delComm.do", produces = "application/json;charset=utf-8")
    @ResponseBody
    public MyGsonView delComm(String commId, Principal principal) {
        MyGsonView gsonView = createGsonView();
        PersonBean person = contendService.querySoaPersonInfo(principal.getName());
        if (person.getPersonId() == null || StringUtils.isBlank(commId)) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        }
        try {
            contendService.delComm(commId, person.getPersonId());
            gsonView.addStaticAttribute(BaseContants.DATA, "");
        } catch (Exception e) {
            LOGGER.error("delComm error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }
}
